#include <bits/stdc++.h>
using namespace std;
#define N 1100
int a[N][N], vis[N][N];
int n, m;
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            char c;
            cin >> c;
            a[i][j] = c - '0';
        }
    }

    while (m--)
    {
        memset(vis, 0, sizeof vis);
        int x, y;
        cin >> x >> y;
        int ans = 1;
        queue<pair<int, int>> q;
        q.push({x, y});
        vis[x][y] = 1;
        while (!q.empty())
        {
            auto t = q.front();
            q.pop();
            int xx = t.first, yy = t.second;
            for (int i = 0; i < 4; i++)
            {
                int tx = xx + dx[i], ty = yy + dy[i];
                if (tx >= 1 && tx <= n && ty >= 1 && ty <= n)
                {
                    if (a[xx][yy] == 1 && a[tx][ty] == 0 && !vis[tx][ty])
                    {
                        ans++;
                        vis[tx][ty] = 1;
                        q.push({tx, ty});
                    }
                    else if (a[xx][yy] == 0 && a[tx][ty] == 1 && !vis[tx][ty])
                    {
                        ans++;
                        vis[tx][ty] = 1;
                        q.push({tx, ty});
                    }
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}